package com.itheima.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Dto.OrdersDto;
import com.itheima.common.R;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> OrderSubmit(@RequestBody Orders orders) {

        ordersService.submit(orders);
        return R.success("下单成功");

    }

    /**
     * 后台查询订单明细
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime) {

        //分页构造器对象
        Page<Orders> pageInfo = new Page<>(page,pageSize);

        //构造条件查询对象
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        //添加查询条件，使用范围查询动态SQL
        lqw.like(number != null, Orders::getNumber, number)
                .gt(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime)
                .lt(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);

        ordersService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /**
     * 下单完成查询订单数据
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("userPage")
    public R queryPage(Integer page,Integer pageSize) {

        Page<Orders> pageInfo = new Page<>(page,pageSize);
        ordersService.page(pageInfo);
        List<Orders> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();

        List<OrdersDto> collect = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);

            //订单明细
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(OrderDetail::getOrderId, ordersDto.getNumber());
            List<OrderDetail> details = orderDetailService.list(lqw);
            ordersDto.setOrderDetails(details);
            return ordersDto;
        }).collect(Collectors.toList());

        Map map = new HashMap();
        map.put("total",total);
        map.put("records",collect);

        return R.success(map);
    }

    /**
     * 订单派送
     * @param orders
     * @return
     */
    @PutMapping
    public R updateStatus(@RequestBody Orders orders) {

        LambdaUpdateWrapper<Orders> lqw = new LambdaUpdateWrapper<>();

        lqw.eq(Orders::getStatus,orders.getStatus());
        lqw.set(Orders::getStatus,orders.getStatus());

        ordersService.update(lqw);
        return R.success("派送订单成功");
    }

    /**
     * 导出到Excel表格
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/export")
    public R export(HttpServletResponse response) throws IOException {

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        List<Orders> list = ordersService.list(lqw);
        ExcelWriter writer = ExcelUtil.getWriter(true);

        ArrayList<String> column = new ArrayList<>();
        column.add("订单号");
        column.add("订单状态");
        column.add("用户");
        column.add("手机号");
        column.add("地址");
        column.add("下单时间");
        column.add("实收金额");

        List<Map<String,Object>> data = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String,Object> dataMap = new HashMap<>();
            Orders orders = list.get(i);
            dataMap.put("订单号",orders.getId().toString());
            dataMap.put("订单状态",orders.getStatus());
            dataMap.put("用户",orders.getUserId().toString());
            dataMap.put("手机号",orders.getPhone());
            dataMap.put("地址",orders.getAddress());
            dataMap.put("下单时间",orders.getOrderTime());
            dataMap.put("实收金额",orders.getAmount());
            data.add(dataMap);
        }

        writer.setColumnWidth(0,30);
        writer.setColumnWidth(1,30);
        writer.setColumnWidth(2,30);
        writer.setColumnWidth(3,30);
        writer.setColumnWidth(4,30);
        writer.setColumnWidth(5,30);
        writer.setColumnWidth(6,30);
        writer.write(data);

        String fileName = URLEncoder.encode("订单明细", "UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream);
        outputStream.close();
        return R.success("导出Excel成功");

    }

}
